#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime, \
    func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""user_base collection has 
   userid:     用户id (int)
   ctime:      注册时间(datetime)
"""


class BlackUserItem(object):

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.userid)


black_user_table = Table(
    'black_user', metadata,
    Column('id', Integer, primary_key=True),
    Column('userid', Integer, index=True, unique=True, nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(BlackUserItem, black_user_table)

def create_black_user_table_if_not_exist():
    metadata.create_all(engine)

def add_black_user_item(p_item):
    item = BlackUserItem()
    item.userid = p_item['userid']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_black_user_all_with_begin_limit(p_begin, p_limit):
    try:
        session = Session()
        items = session.query(BlackUserItem).offset(p_begin).limit(p_limit).all()
        if not items:
            return []
        return [item.to_dict()['userid'] for item in items]
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def get_black_user_all():
    try:
        session = Session()
        items = session.query(BlackUserItem).all()
        if not items:
            return []
        return [item.to_dict()['userid'] for item in items]
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def drop_black_user_by_userid(p_userid):
    try:
        session = Session()
        items = session.query(BlackUserItem).filter_by(userid=p_userid).delete()
        session.flush()
        session.commit()
        if not items:
            return False
        else:
            return True
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def get_black_user_count():
    try:
        session = Session()
        item = session.query(func.count(BlackUserItem.userid)).first()
        return item[0] if item else None
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == "__main__":
    create_black_user_table_if_not_exist()
    item = {u'userid': 1234}
    add_black_user_item(item)